<template>
  <div
    :class="ismobile ? 'no-scroll' : ''"
    class="w-fill h-auto bg-[#1a2c38] w-full m-auto max-w-[1200px] min-375 text-white"
  >
    <iframe
      class="iframe_src bg-[#0e1325] w-full m-auto mt-2 md:mt-8"
      :src="game_url"
      ref="iframe"
      frameborder="0"
    ></iframe>
    <!-- <div
      id="iframeId"
      class="iframe_src bg-[#0e1325] w-full m-auto mt-2 md:mt-8"
    ></div> -->
    <div
      class="flex items-center justify-between bg-[#0f212e] p-4 text-[#b1bad3] text-base font-semibold"
    >
      <p>{{ main.currentGame.name }}</p>
      <div class="flex items-center">
        <!-- <svg-icon
          class="text-[18px] mr-2 w-1 h-1 text-[#2f4553] hover:text-white cursor-pointer"
          name="Logout"
          width="100px"
          height="100px"
        /> -->
        <!-- <span class="cursor-pointer text-2xl mr-3"> × </span> -->

        <div class="cursor-pointer" @click="clickStar()">
          <svg-icon
            v-if="main.currentGame.is_collect == 0"
            class="text-[26px] text-[#b1bad3] hover:text-white star1"
            name="星星1"
          />
          <svg-icon v-else class="text-[26px] text-white star2" name="星星2" />
        </div>
        <svg-icon
          v-if="!ismobile"
          @click="toggle"
          class="text-[20px] ml-4 text-[#b1bad3] star1 cursor-pointer hover:text-white"
          name="实时数据"
        />
        <svg-icon
          @click="onToggle()"
          class="text-[20px] ml-4 text-[#b1bad3] star1 cursor-pointer hover:text-white"
          name="全屏"
        />
        <svg
          @click="router.push('/casino')"
          t="1736142182749"
          class="cursor-pointer icon text-[24px] text-[#b1bad3] hover:text-white star1 ml-4"
          viewBox="0 0 1024 1024"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          p-id="1472"
          xmlns:xlink="http://www.w3.org/1999/xlink"
          width="24"
          height="24"
        >
          <path
            d="M511.991851 1023.982934c-282.320581 0-511.991381-229.679334-511.991382-511.991382 0-282.277915 229.670801-511.991381 511.991382-511.991381a510.813801 510.813801 0 0 1 344.271538 133.032427 42.640349 42.640349 0 0 1 2.901284 60.244319c-15.829067 17.493039-42.793946 18.730351-60.286985 2.901285A425.840298 425.840298 0 0 0 511.991851 85.332068c-235.26004 0-426.659485 191.399445-426.659485 426.659484 0 235.302706 191.399445 426.659485 426.659485 426.659485 105.982216 0 207.569839-39.082009 286.032518-110.078147a42.606216 42.606216 0 0 1 60.244319 2.986616 42.640349 42.640349 0 0 1-2.986616 60.244319c-94.163748 85.246565-216.103029 132.179108-343.290221 132.179109"
            fill="#b1bad3"
            p-id="1473"
          ></path>
          <path
            d="M885.975955 552.447404H341.328057c-23.466272 0-42.665948-19.199677-42.665948-42.665948s19.199677-42.665948 42.665948-42.665948h544.647898L792.989787 371.449918a42.77688 42.77688 0 0 1 0-60.329651 42.77688 42.77688 0 0 1 60.329651 0l158.205337 162.770593a42.58915 42.58915 0 0 1 12.356059 32.946646 42.77688 42.77688 0 0 1 0 5.879367 42.58915 42.58915 0 0 1-12.356059 32.955179L853.319438 708.442645a42.77688 42.77688 0 0 1-60.329651 0 42.77688 42.77688 0 0 1 0-60.329651l92.986168-95.674123z"
            fill="#b1bad3"
            p-id="1474"
          ></path>
        </svg>
      </div>
    </div>
    <div v-if="!ismobile" class="w-full mt-[12px] bg-[#0f212e]">
      <Rank />
    </div>
    <div v-if="!ismobile" class="flex text-xl font-semibold items-center">
      <svg-icon class="text-[28px] text-white star1 mr-2 my-4" name="res" />
      {{ $t("page.footer.Hot") }}
    </div>
    <gameBox v-if="!ismobile" :games="sameGams" />
    <realTimeDataDialog :visible="boolean" @close="toggle" />
  </div>
</template>
<script setup>
import {
  nextTick,
  ref,
  onMounted,
  onDeactivated,
  defineAsyncComponent,
  watch,
  onUnmounted
} from "vue";
import { useRouter, useRoute } from "vue-router";
import { mainAct } from "../../store/activeda";
import Rank from "./components/rank.vue";
import { gameCollect, gameCollectList, gameSame } from "../../api/casion";
import screenfull from "screenfull";
import { useBoolean } from "@/hooks/useBoolean";
const gameBox = defineAsyncComponent(() =>
  import("../../components/gameSwiper/gameBox.vue")
);
import realTimeDataDialog from "./components/realTimeDataDialog.vue";
import { isMobile } from "@/utils/isMobile";

import { eventBus } from "@/utils/eventBus";
import { onBeforeRouteLeave } from "vue-router";
// beforeRouteEnter(() => {
//   console.log("7777777777777", route.query.userToken);
//   // eventBus.emit("iframe-route");
//   // A  B
//   // A edge -> B 谷歌(token)
//   // url + token后八位（A）-> B 谷歌(token)
//   // B的逻辑先取本地后8位 对比 不一样就肯定有问题
// });
const sameGams = ref([]);
const iframe = ref(null);
const main = mainAct();
const router = useRouter();
const route = useRoute();
const game_url = ref("");

// 动态创建 iframe
const createIframe = gameUrl => {
  game_url.value = gameUrl;
  // 确保在创建新的 iframe 之前，先清理旧的 iframe
  // clearIframe()
  //   .then(() => {
  //     const container = document.getElementById("iframeId");
  //     // 动态创建 iframe
  //     const iframe = document.createElement("iframe");
  //     iframe.src = gameUrl; // 设置 URL
  //     iframe.frameBorder = 0; // 去掉边框
  //     iframe.className = "w-full h-full"; // 设置类名
  //     iframe.allow = "fullscreen"; // 添加允许权限，根据需要扩展
  //     iframe.onload = () => console.log("Iframe loaded successfully");
  //     iframe.onerror = () => console.error("Failed to load iframe.");
  //     container.appendChild(iframe); // 添加到容器
  //     iframe.value = iframe;
  //     console.error(
  //       "iframe---------------------------------:",
  //       iframe,
  //       iframe.value
  //     );
  //   })
  //   .catch(err => {
  //     console.error("Error clearing iframe:", err);
  //   });
};

// 销毁 iframe
function clearIframe() {
  return new Promise((resolve, reject) => {
    const container = document.getElementById("iframeId");
    if (!container) {
      console.warn("Container for iframe not found.");
      resolve();
      return;
    }

    const iframe = container.querySelector("iframe");
    if (iframe) {
      try {
        // 设置 iframe 为空白页面，释放资源
        iframe.src = "about:blank"; // 或者 iframe.src = "javascript:void(0)";
      } catch (e) {
        iframe.src = "javascript:void(0)";
        console.error("Error setting iframe to blank:", e);
      }

      // 由于跨域问题，直接访问 iframe 内部内容会失败，因此不再清理内部文档
      // 但我们通过清空 src 和移除 iframe 元素，确保资源被释放

      try {
        // 清空 iframe 所占的 DOM 容器
        container.innerHTML = "";
        console.log("Iframe and its resources cleared.");
        resolve();
      } catch (e) {
        console.error("Error clearing iframe container:", e);
        reject(e);
      }
    } else {
      // 如果没有找到 iframe，则直接 resolve
      resolve();
    }
  });
}

watch(
  () => route.query.game_url,
  (newVal, oldVal) => {
    if (newVal) {
      nextTick(() => {
        game_url.value = newVal;
        createIframe(game_url.value);
      });
    }
  },
  { immediate: true, deep: true }
);

const { boolean, toggle } = useBoolean();
// const { game_url } = route.query; // 获取路由参数
// 是否全屏
const isFullscreen = ref(false);
// 监听变化
const change = () => {
  isFullscreen.value = screenfull.isFullscreen;
};
const ismobile = ref(false);

const handleResize = () => {
  console.log("handleResize", isMobile());
  ismobile.value = isMobile();
};

// 切换事件
const onToggle = () => {
  console.log("iframe.value", screenfull, iframe);
  if (iframe.value) {
    nextTick(() => {
      screenfull.toggle(iframe.value);
    });
  } else {
    console.error("Iframe element not found.");
  }

  // screenfull.enabled && screenfull.toggle(iframe.value);
  // screenfull.toggle(iframe.value);
  // screenfull.request();
  // screenfull.toggle(iframe.value);
};

// console.log("游戏传参-" + JSON.stringify(game_url));
const clickStar = async () => {
  // console.log(main.currentGame.code);
  let data = {
    game_code: main.currentGame.code
  };
  let res = await gameCollect(data);
  console.log(res);
  if (res.errno == 0) {
    // 请求收藏夹列表
    // getList();
    if (main.currentGame.is_collect == 1) {
      main.currentGame.is_collect = 0;
    } else {
      main.currentGame.is_collect = 1;
    }
  }
};
const getSameList = async () => {
  let data = {
    game_code: main.currentGame.code,
    page: 1,
    page_size: 7
  };
  let res = await gameSame(data);
  if (res.errno == 0) {
    console.log(res.data.list);
    res.data.list.forEach(item => {
      if (!item.img_url.startsWith("http")) {
        item.img_url = main.static_base_url + item.img_url;
      }
    });
    sameGams.value = res.data.list;
  }
};
// 使用原生事件来替代 screenfull 事件监听
const fullscreenChangeHandler = () => {
  console.log("Fullscreen state changed");
  // 添加处理逻辑
  isFullscreen.value = screenfull.isFullscreen;
  console.log("isFullscreen", isFullscreen.value);
};

onMounted(() => {
  // main.isLoading =false;
  // handleResize();
  handleResize();
  window.addEventListener("resize", handleResize);
  // 监听全屏变化
  document.addEventListener("fullscreenchange", fullscreenChangeHandler);
  document.addEventListener("webkitfullscreenchange", fullscreenChangeHandler);
  //去除百分号和数字
  main.currentGame.name = main.currentGame?.name?.replace(/(\d+%)/, "");
  getSameList();
});

// 删除侦听器
onDeactivated(() => {
  if (screenfull.enabled && typeof screenfull.off === "function") {
    screenfull.off("change", change);
  }
  window.removeEventListener("resize", handleResize);
  document.removeEventListener("fullscreenchange", fullscreenChangeHandler);
  document.removeEventListener(
    "webkitfullscreenchange",
    fullscreenChangeHandler
  );
});

onUnmounted(() => {
  if (screenfull.enabled && typeof screenfull.off === "function") {
    screenfull.off("change", change);
  }
  window.removeEventListener("resize", handleResize);
  document.removeEventListener("fullscreenchange", fullscreenChangeHandler);
  document.removeEventListener(
    "webkitfullscreenchange",
    fullscreenChangeHandler
  );
});

const socket = ref(null);

onBeforeRouteLeave(() => {
  clearIframe().then(() => {
    eventBus.emit("game_leave");
  });
  // 主动触发
});
</script>

<style scoped lang="less">
.iframe_src {
  height: 41rem;
}

@media (max-width: 600px) {
  .iframe_src {
    width: 90vw;
    height: calc(100svh - 148px) !important;
    -webkit-overflow-scrolling: touch;
    overflow: scroll;
  }
}

.no-scroll {
  position: fixed;
  height: 100%;
  overflow: hidden !important;
}
</style>
